<template>
  <div class="pageWrapper">
    <SearchBar @onSearch="handleSearch" @childFn="resetForm">
      <SearchBarItem label="商户名称：" :labelLg="8">
        <Input type="text" v-model="searchModule.merchantName" placeholder="请输入机构编码" clearable/>
      </SearchBarItem>
      <SearchBarItem label="商户编码：" :labelLg="8">
        <Input type="text" v-model="searchModule.merchantCode" placeholder="请输入商户编码" clearable/>
      </SearchBarItem>
      <SearchBarItem label="产品名称：" :labelLg="8">
        <Input type="text" v-model="searchModule.productName" placeholder="请输入产品名称" clearable/>
      </SearchBarItem>
      <SearchBarItem label="产品编码：" :labelLg="8">
        <Input type="text" v-model="searchModule.productCode" placeholder="请输入产品编码" clearable/>
      </SearchBarItem>
      <SearchBarItem label="业务侧产品编码：" :labelLg="8">
        <Input type="text" v-model="searchModule.productCodeBusiness" placeholder="请输入业务侧产品编码" clearable/>
      </SearchBarItem>
      <SearchBarItem label="支付渠道：" :labelLg="8">
        <Select v-model="searchModule.paymentChannelCode" placeholder="请选择支付渠道" clearable>
          <Option v-for="(item, index) in selectChannelList" :key="index" :value="item.key">{{ item.value }}</Option>
        </Select>
      </SearchBarItem>
      <SearchBarItem label="业务场景：" :labelLg="8">
        <Select v-model="searchModule.scenario" placeholder="请选择业务场景" clearable>
          <Option v-for="(item, index) in selectScenario" :key="index" :value="item.key">{{ item.value }}</Option>
        </Select>
      </SearchBarItem>
      <SearchBarItem label="创建时间：" :labelLg="8">
        <DatePicker type="date" v-model="searchModule.createdDt" ref="createDatePicker" :options="timeOptions"
                    format="yyyy-MM-dd" @on-change="changeCreated" placeholder="创建时间"></DatePicker>
      </SearchBarItem>
    </SearchBar>
    <RemoteTable :namespace="namespace" :columns="columns" @onSortChange="onSortChange" ref="tableData">
      <template #extra>
        <Authc permissions="trade:merchant:merchandise:edit">
          <Button type="primary" @click="handleClick('add')">新增</Button>
        </Authc>
        <Authc permissions="trade:merchant:merchandise:export">
          <Button type="primary" @click="exportExcel">导出</Button>
        </Authc>
      </template>
    </RemoteTable>

    <!-- 编辑弹窗 -->
    <Modal width="700" v-model="isShow" :visible.sync="isShow" :title="title">
      <Loading :loading="false">
        <Form ref="dataModule" :label-width="130" :model="dataModule" :rules="ruleValidate">
          <FormItem label="所属商户：" prop="merchantCode">
            <div v-if="showCode">{{ dataModule.merchantName }}</div>
            <Select v-else v-model="dataModule.merchantCode" :label-in-value="true" filterable clearable
                    @on-change="bandleMerchant">
              <Option v-for="(item, index) in merchantNameSelect" :key="index" :value="item.key">{{
                  item.value
                }}
              </Option>
            </Select>
          </FormItem>

          <FormItem label="商户编码：" v-show="showCode">
            <div>{{ dataModule.merchantCode }}</div>
          </FormItem>
          <FormItem label="产品编码：" v-show="showCode">
            <div>{{ dataModule.productCode }}</div>
          </FormItem>

          <FormItem label="产品编码：" prop="productCode" v-show="modalActionType==='add'">
            <Input type="text" v-model="dataModule.productCode" placeholder="请填写，长度在4至64之间" minlength="25"
                   maxlength="64"/>
          </FormItem>
          <p v-show="modalActionType==='add'" style="margin:-2px 0 0 130px;color: red">*产品编码不填则系统自动生成,请确保填入的编码正确！！</p>
          <FormItem label="产品名称：" prop="productName">
            <Input type="text" v-model="dataModule.productName" placeholder="请填写，字数不超过25" maxlength="25"/>
          </FormItem>
          <FormItem label="产品详情：">
            <Input type="text" v-model="dataModule.productDetail" placeholder="请填写，字数不超过32" :maxlength="maxlength"/>
          </FormItem>
          <FormItem prop="scenario" label="业务场景：">
            <Select v-model="dataModule.scenario" clearable>
              <Option v-for="(item, index) in selectScenario" :key="index" :value="item.key">{{ item.value }}</Option>
            </Select>
          </FormItem>
          <FormItem label="业务侧产品编码：">
            <Input type="text" v-model.trim="dataModule.productCodeBusiness" placeholder="请填写，字数不超过64"
                   maxlength='64'/>
          </FormItem>
          <FormItem label="成本价格：" prop="costType">
            <Radio-group v-model="dataModule.costType" @on-change="changeCost">
              <Radio v-for="item in selectPie" :key="item.value" :label="item.key">{{ item.value }}</Radio>
            </Radio-group>
          </FormItem>

          <FormItem prop="costPrice" v-if="dataModule.costType == '1'">
            <Input type="text" v-model="dataModule.costPrice" number placeholder="请填写金额">
              <span slot="append">元</span>
            </Input>
          </FormItem>
          <FormItem prop="costPrice" v-if="dataModule.costType == '2'">
            <Input type="text" v-model="dataModule.costPrice" number placeholder="请填写百分比">
              <span slot="append">%</span>
            </Input>
          </FormItem>

          <FormItem prop="paymentChannel" label="支付渠道：" v-if="dataModule.merchantCode">
            <Select v-model="dataModule.paymentChannel" clearable>
              <Option v-for="(item, index) in selectChannel" :key="index" :value="item.key">{{ item.value }}</Option>
            </Select>
          </FormItem>
        </Form>
      </Loading>
      <div slot="footer">
        <Button style="margin-left: 8px" @click="handleSubmitCancel('dataModule')">取消</Button>
        <Button type="primary" :disabled="submitAble" @click="handleSubmit('dataModule')">确定</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import {
  Button,
  Input,
  Modal,
  Message,
  Col,
  Row,
  Form,
  FormItem,
  DatePicker,
  Select,
  Option,
  Card,
  RadioGroup,
  Radio
} from "view-design";
import Loading from "@/components/Loading";
import RemoteTable from "@/components/RemoteTable";
import RemoteSelect from "@/components/RemoteSelect";
import SearchBar from "@/components/SearchBar";
import {namespace} from "../module/merchandise";
import Authc from "@/components/Authc";
import Action from "./Action";
import config from "@/utils/config";
import appService from "@/utils/appService";
import util from "@/utils/util";

export default {
  name: 'tables_page',
  components: {
    Loading,
    RemoteTable,
    SearchBar,
    SearchBarItem: SearchBar.SearchBarItem,
    RemoteSelect,
    Authc,
    Action,
    Button,
    Input,
    Modal,
    Message,
    Col,
    Row,
    Form,
    FormItem,
    DatePicker,
    Select,
    Option,
    Card,
    RadioGroup,
    Radio
  },
  data() {
    const validateProductCode = (rule, value, callback) => {
      if (value && (value.length < 5 || value.length > 64)) {
        callback(new Error("商品编码长度在4至64之间"))
      } else {
        callback()
      }
    };
    return {
      maxlength: 32,
      title: '',
      isShow: false,
      showCode: false,
      namespace: namespace,
      modalActionType: '',//模态框操作类型
      loading: true,
      dataModule: {},
      searchModule: {},
      tableData: [],
      submitAble: false,
      ruleValidate: {
        merchantCode: [{required: true, message: '请选择', trigger: 'change'}],
        productCode: [{required: false, validator: validateProductCode, trigger: 'blur'}],
        productName: [{required: true, message: '请填写', trigger: 'blur'}],
        scenario: [{required: true, message: '请选择', trigger: 'change'}],
        paymentChannel: [{required: true, message: '请选择', trigger: 'change'}],
        costType: [{required: true, type: 'number', message: '请选择', trigger: 'change'}],
        costPrice: [{required: true, type: 'number', message: '请填写正确金额', trigger: 'blur'}]
      },
      columns: [
        {
          title: '序号',
          type: 'index',
          width: 80,
          align: 'center'
          // fixed: 'left'
        },
        {
          title: '产品名称',
          key: 'productName',
          minWidth: 180,
          align: 'center'
          // fixed: 'left'
        },
        {
          title: '产品编码',
          key: 'productCode',
          minWidth: 280,
          align: 'center'
        },
        {
          title: '所属商户',
          key: 'merchantName',
          minWidth: 210,
          align: 'center'
        },
        {
          title: '产品详情',
          key: 'productDetail',
          minWidth: 150,
          align: 'center'
        },
        {
          title: '业务场景',
          key: 'scenarioCn',
          minWidth: 150,
          align: 'center'
        },
        {
          title: '业务侧产品编码',
          key: 'productCodeBusiness',
          minWidth: 150,
          align: 'center'
        },
        {
          title: '成本价格',
          key: 'costType',
          minWidth: 150,
          align: 'center',
          render: (h, params) => {
            if (params.row.costType == '1') {
              let item = params.row.costPrice;
              return h('span', util.toMoney(item));
            } else {
              return h('span', [
                h('span', params.row.costPrice + '%'),
                h('span', '售价')
              ])
            }
          }
        },
        {
          title: "创建时间",
          key: "createdDt",
          minWidth: 150,
          align: "center"
        },
        {
          title: "操作",
          key: "action",
          // fixed: "right",
          align: "center",
          permissions: ["trade:merchant:merchandise"],
          width: 130,
          render: function (h, data) {
            return h(Action, {
              props: {
                row: data.row
              }
            });
          }
        }
      ],
      merchantNameSelect: [],
      selectScenario: [], // 业务场景
      selectChannel: [], // 关联商户-渠道
      selectChannelList: [], // 全部渠道渠道
      addType: true,
      selectPie: [
        {
          key: 1,
          value: '固定金额'
        },
        {
          key: 2,
          value: '售价比例'
        }
      ],
      changeCostType: '',
      channelItem: '', /** 获取渠道所需的商户参数 */
      timeOptions: {
        disabledDate: date => {
          return date && date.valueOf() > Date.now();
        }
      }
    }
  },
  created() {
    /** 如果 url 没有带参数，就重置请求参数 **/
    this.$store.commit(`${namespace}/reviseQuery`);
    this.getSelect();
    this.getAllChannel();

  },
  watch: {
    'changeCostType'(newValue, oldValue) {
      if (newValue) {
        this.$set(this.dataModule, 'costPrice', '')
      }
    }
  },
  methods: {
    changeCreated(e) {
      this.searchModule.createdDt = e;
    },
    changeCost(val) {
      this.changeCostType = val;
    },
    // 清空事件；
    resetForm() {
      this.$set(this.searchModule, 'merchantName', '')
      this.$set(this.searchModule, 'merchantCode', '')
      this.$set(this.searchModule, 'productName', '')
      this.$set(this.searchModule, 'productCode', '')
      this.$set(this.searchModule, 'productCodeBusiness', '')
      this.$set(this.searchModule, 'paymentChannelCode', '')
      this.$set(this.searchModule, 'paymentChannel', '')
      this.$set(this.searchModule, 'scenario', '')

      // 清空时间选择
      this.$refs["createDatePicker"].handleClear();
    },
    // 导出
    async exportExcel() {
      try {
        let res = await this.$store.dispatch(`${namespace}/exportExcel`, this.searchModule);
        let link = document.createElement('a');

        util.exportExcle(res, '商品管理表');
      } catch (error) {
        this.$Message.error({
          content: '导出失败'
        })
      }
    },
    // 所属商户
    async getMerchant() {
      try {
        let res = await this.$store.dispatch(`${namespace}/getMerchant`);
        if (res.data.ret === 0) {
          let data = res.data.data;
          this.merchantNameSelect = data.map(({merchantName, merchantCode}) => {
            return {
              value: merchantName,
              key: merchantCode
            }
          })

        }
      } catch (error) {
        this.$Message.error({
          content: error
        })
      }
    },

    /** 根据商户获取对应的的渠道 */
    async getMerchantChannel(merchantCode) {
      try {
        let params = {
          merchantCode: merchantCode
        }
        let res = await this.$store.dispatch(`${namespace}/getMerchantPaymentChannelByMerchantCode`, params);
        if (res.data.ret === 0) {
          let data = res.data.data;
          this.selectChannel = data.map(({paymentChannelCode, paymentChannelName}) => {
            return {
              value: paymentChannelName,
              key: paymentChannelCode
            }
          })
        } else {
          this.selectChannel = []
        }
      } catch (error) {
        this.$Message.error({
          content: error
        })
        this.selectChannel = []
      }
    },
    /** 获取全部渠道 */
    async getAllChannel() {
      try {
        let params = {
          currentPage: 1,
          pageSize: 9999
        }
        let res = await this.$store.dispatch(`${namespace}/allChannel`, params);
        if (res.data.ret === 0) {
          let data = res.data.data.list;
          this.selectChannelList = data.map(({paymentChannelCode, paymentChannelName}) => {
            return {
              key: paymentChannelCode,
              value: paymentChannelName
            }
          })
        }
      } catch (error) {
        this.$Message.error({
          content: error
        })
      }
    },
    // 字典
    getSelect() {
      this.$store.dispatch(`${namespace}/getMerchantSearchKey`).then((res) => {
        if (res && res.data && res.data.errorCode === 0) {
          let data = res.data.data;
          // this.selectChannelList = data.merchantPaymentChannel; // 渠道
          this.selectScenario = data.merchantScenario; // 场景
        }
      })
    },
    bandleMerchant(val) {
      this.dataModule.merchantName = val ? val.label : '';
      if(val){
        this.getMerchantChannel(val.value); /** 再次调接口获取商户对应的渠道 */
      }else{
        this.selectChannel = []
      }

    },
    handleSubmitCancel(formName) {
      this.isShow = false;
      this.submitAble = false;
      this.$refs[formName].resetFields();
    },
    handleSubmit(formName) {
      this.submitAble = true;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.addType) {
            this.$store.dispatch(`${namespace}/save`, this.dataModule).then(res => {
              if (res && res.errorCode === 0) {
                this.$Message.success(res.msg)
                this.$store.dispatch(`${namespace}/query`);
              } else {
                this.$Message.error({
                  content: res.msg
                })
              }
            })
          } else {
            this.$store.dispatch(`${namespace}/localUpdate`, this.dataModule).then(res => {
              if (res && res.errorCode === 0) {
                this.$Message.success(res.msg)
                this.$store.dispatch(`${namespace}/query`);
              } else {
                this.$Message.error({
                  content: res.msg
                })
              }
            })
          }
          this.isShow = false;
          this.submitAble = false;
        } else {
          console.log('error submit!!')
          this.submitAble = false;
          return false
        }
      })
    },
    handleClick(type) {
      if (type === 'add') {

        this.resetFormAll();
        this.getMerchant();
        this.addType = true;
        // switch (type) {
        //   case 'add':
        this.showCode = false;
        this.isShow = true;
        this.title = '新增商品信息';
        this.modalActionType = 'add'
        this.dataModule = {};
      }
      //     break
      //   case 'edit':
      //     break
      //   case 'delete':

      //     break
      //   default:
      // }
    },
    // 重置
    resetFormAll() {
      this.$refs['dataModule'].resetFields()
    },
    handleSearch() {
      let pageSize = {
        currentPage: 1,
        pageSize: 10
      }
      this.$store.dispatch(`${namespace}/query`, {...this.searchModule, ...pageSize});
    },
    onSortChange(sort) {
      if (sort.order === "normal") {
        this.queryParam.order = [];
      } else {
        this.queryParam.order = [sort.key + " " + sort.order];
      }
      this.handleSearch();
    },

    // resetForm() {
    //   this.$refs["formArea"].resetFields();
    // }
  },
  async mounted() {
    this.$bus.$on('actionType', (data) => {
      let id = data.id;
      let merchantCode = data.merchantCode;
      if (data.type === 'edit') {
        this.title = '编辑商品信息';
        this.isShow = true;
        this.showCode = true;
        this.addType = false;
        this.resetFormAll();
        this.$store.dispatch(`${namespace}/getDetail`, id).then(res => {
          if (res && res.ret === 0) {
            this.dataModule = res.data;
            this.dataModule.costType = Number(res.data.costType);
            // 查询商户的渠道信息
            this.getMerchantChannel(merchantCode)
          }
        });
      } else if (data.type === 'delete') {
        Modal.confirm({
          render: (h, params) => {
            return h('div', [
              h('div', {
                style: "margin-bottom:10px;vertical-align: middle;font-size: 16px;color: #17233d;font-weight: 700;"
              }, '提示'),
              h('div', {
                class: 'selfConfirm',
              }, '确定删除?')
            ]);
          },
          onOk: () => {
            return this.$store.dispatch(`${namespace}/delete`, id).then((res) => {
              if (res && res.ret === 0) {
                this.$Message.success(res.msg);
                this.$store.dispatch(`${namespace}/query`);
              } else {
                this.$Message.warning(res.msg);
              }
            })
          }
        })
      }
    });
  },
  beforeDestroy() {
    this.$bus.$off('actionType');
  }
}
</script>
